/* A simple Node.js based web frontend for the Pololu Mini Maestro 12
 * channel servo controller
 *
 * Usage:
 * - Set the comport of the Maestro command port below
 * - Command servo positions with the following http request
 *		http://127.0.0.1:1337/maestro/?0=1500&1=1500&2=1500
 *	where the GET string (everything after the ?) is made up of channel=value pairs, separated by &'s
 *
 */



var SerialPort = require("serialport").SerialPort
var http = require('http');
var url = require('url');

var COMPORT = "COM17";
var PORTNO = 1337;
 
var serialPort = new SerialPort(COMPORT, {
	baudrate: 115200
});
  
serialPort.on("open", function () {
	console.log(COMPORT + " open...");

	http.createServer(function (req, res) {
		var myURL = url.parse(req.url,true);
		var command = myURL.path.split("/")[1];
		var positions = myURL.query;
		if (command == "maestro") {
				for (var i = 0; i< 12; i++) {
				if (positions[i] !== undefined) {
					var buf = new Buffer(4);

					buf[0] = 0x84;
					buf[1] = parseInt(i);
					var position = parseInt(positions[i]);

					buf[2] = (position*4) & 0x7F;
					buf[3] = ((position*4) >> 7) & 0x7F;

					serialPort.write(buf, function(err, results) {
						res.writeHead(200, {'Content-Type': 'text/plain'});
						if (err === undefined) {
							res.end("OK!");
						} else {
							res.end("ERROR " + err);
						}
					}); 
				}
			}
		}
	}).listen(PORTNO, '0.0.0.0');
	console.log("Listening on " + PORTNO + "...");
});